import { createRouter, createWebHistory } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { staticRoutes, layoutRoute } from './routes';
import http from '@/utils/request';
import { usePermissionStore } from '@/stores/permission';

const router = createRouter({
  history: createWebHistory(),
  routes: [...staticRoutes, layoutRoute],
  scrollBehavior: () => ({ top: 0 })
});

const whiteList = ['/login', '/404', '/front']; // 白名单定义

router.beforeEach(async (to, from, next) => {
  if (to.meta.title) {
    document.title = `${to.meta.title} - 小花在线图书馆`;
  } else {
    document.title = '小花在线图书馆';
  }

  const userStore = useUserStore();
  const permissionStore = usePermissionStore();

  // 1. 白名单检查
  if (whiteList.some(path => to.path.startsWith(path))) {
    next();
    return;
  }

  // 2. 权限路由标识
  const isAuthRoute = to.path.startsWith('/dashboard/');

  // 3. 未登录访问受保护路由
  if (!userStore.library_token && isAuthRoute) {
    next(`/login?redirect=${encodeURIComponent(to.fullPath)}`);
    return;
  }

  // 4. 已登录处理逻辑
  if (userStore.library_token) {
    // 4.1 获取用户信息（无论是否已有roles）
    if (!userStore.library_users.roles.length) {
      try {
        const infoRes = await http.get('/user/getInfo');
        userStore.roles = infoRes.data.roles;
      } catch (error) {
        userStore.logout();
        next('/login');
        return;
      }
    }

    // 4.2 动态路由处理
    if (userStore.roles.length && !permissionStore.hasGenerated) {
      // 生成权限路由
      await permissionStore.generateRoutes(userStore.roles);

      // 清除旧路由（防止重复添加）
      permissionStore.routes.forEach(route => {
        if (router.hasRoute(route.name)) {
          router.removeRoute(route.name);
        }
      });

      // 添加新路由
      permissionStore.routes.forEach(route => {
        router.addRoute('layoutRoute', {
          ...route,
          path: route.path.replace(/^\//, '')
        });
      });

      // 强制重新导航（关键）
      permissionStore.setHasGenerated(true);
      // 添加路径修正逻辑，防止无限循环
      const redirectPath = to.redirectedFrom?.path || to.path;
      next({ path: redirectPath, replace: true, query: to.query, hash: to.hash });
      return;
    }

    // 4.3 已登录访问登录页跳转
    if (to.path === '/login') {
      next('/dashboard');
      return;
    }
  }

  next();
});